package com.bookstore.servlet;

import com.bookstore.utils.DataConsts;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/imgUpload.do")
public class UploadImgServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(request)) {
            //创建FileItemFactory 工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类 ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                //解析上传的数据 得到每个表单项FileItem
                List<FileItem> list = servletFileUpload.parseRequest(request);

                //循环判断：每一个表单项是普通文本类型，还是文件类型
                for (int i = 0; i < list.size(); i++) {
                    FileItem fileItem = list.get(i);
                    long timeMills = System.currentTimeMillis();
                    String originalFileName = fileItem.getName();
                    //1.2.jpg ==> "1"  "2"  "jpg"
                    String[] split = originalFileName.split("\\.");
                    String s = split[split.length - 1];
                    //获取当前上传文件的后缀名
                    String newFileName = new StringBuilder(s).insert(0, ".").insert(0, timeMills).toString();
                    //生成一个按照规则的文件名
                    fileItem.write(new File(DataConsts.IMG_SAVE_LOCAL_PATH + newFileName));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
